import json
from flask import Flask, jsonify, request, current_app
from Day09.models import db, User
from rediscluster import StrictRedisCluster
from Day09.cache_tool import UserProfileCache

app = Flask(__name__)
class Config(object):
    SQLALCHEMY_DATABASE_URI = 'mysql://root:mysql@127.0.0.1/toutiao'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = True

    # redis 集群
    REDIS_CLUSTER = [
        {'host': '127.0.0.1', 'port': '7000'},
        {'host': '127.0.0.1', 'port': '7001'},
        {'host': '127.0.0.1', 'port': '7002'},
    ]
app.config.from_object(Config)
app.redis_cluster = StrictRedisCluster(startup_nodes=app.config['REDIS_CLUSTER'])
db.init_app(app)

@app.route('/userinfo/<int:user_id>')
def userinfo(user_id):
    """
    获取用户信息
    :param user_id:
    :return:
    """
    cache_obj = UserProfileCache(user_id)
    user_data = cache_obj.get()
    return jsonify(user_data)

@app.route('/update/<int:user_id>')
def update(user_id):
    user_name = request.args.get('user_name')
    # 1.先更新数据库,再更新缓存.
    user = User.query.get(user_id)
    user.name = user_name
    db.session.add(user)
    db.session.commit()
    # 更新缓存
    key = 'user:{}:profile'.format(user_id)
    user_data = {
        'user_id': user.id,
        'mobile': user.mobile,
        'user_name': user.name,
        'photo': user.profile_photo
    }
    current_app.redis_cluster.setex(key, 5*60, json.dumps(user_data))

    # 2.先删除缓存,再更新数据库
    # 2.1删除缓存
    key = 'user:{}:profile'.format(user_id)
    current_app.redis_cluster.delete(key)
    # 2.2更新数据
    user = User.query.get(user_id)
    user.name = user_name
    db.session.add(user)
    db.session.commit()

    # 3.先更新数据库,再删除缓存
    # 3.1更新数据库
    user = User.query.get(user_id)
    user.name = user_name
    db.session.add(user)
    db.session.commit()
    # 3.2删除缓存
    key = 'user:{}:profile'.format(user_id)
    current_app.redis_cluster.delete(key)
    return '更新成功'

print(app.url_map)

if __name__ == '__main__':
    app.run(host='192.168.226.129', debug=True)